package com.paul.controller;

import java.io.IOException;
import java.lang.reflect.Array;
import java.net.PasswordAuthentication;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.enterprise.inject.Model;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jmx.export.assembler.MethodNameBasedMBeanInfoAssembler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.portlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.domain.User;
import com.paul.service.UserService;

@Controller
public class LoginCl {

	private static Logger logger = Logger.getLogger(LoginCl.class);
	
	@Resource(name = "userService")
    public UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
	
	//验证用户登录
	@RequestMapping("checkUser.do")
	public String checkUser(ModelMap m,HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//response.setContentType("text/html;charset=gbk");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		
		System.out.println("sysout===========得到的用户名是: "+username);
		logger.info("log4j===========得到的用户名是: "+username);
		System.out.println("sysout=++++++++++得到的密码是: "+password);
		logger.info("log4j=++++++++++得到的密码是: "+password);
		
		
		if (userService.checkUser(username, password)) {
			// 合法用户,跳至欢迎界面
			//request.getRequestDispatcher("welcome.jsp").forward(request, response);
			System.out.println("合法用户名是: "+username);
			//request.setAttribute("usr", username);
	
			User user =new User();
			user.setUserId(1);
			user.setUsername("paul");
			user.setPassword("123");
			user.setEmail("532911526@qq.com");
			user.setGrade(0);
			
			User user1 =new User();
			user1.setUserId(2);
			user1.setUsername("robin");
			user1.setPassword("231");
			user1.setEmail("lileitoo@qq.com");
			user1.setGrade(1);
			
			List<Object> al = new ArrayList<Object>();
			al.add(user);
			al.add(user1);
			m.addAttribute("usr", username);
			m.addAttribute("userList",al);
			
			return "welcome";
			
		} else {
			// 非法用户,返回登录界面
			//request.getRequestDispatcher("login.jsp").forward(request, response);
			return "login";
		}
	};
	/*public String checkUser(HttpServletRequest request, HttpServletResponse response,Model m)
			throws ServletException, IOException {

		//response.setContentType("text/html;charset=gbk");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		System.out.println("===========+++++++============得到的用户名是: "+username);
		System.out.println("+++++++++++++++===============++++++++++得到的密码是: "+password);
		
		if (userService.checkUser(username, password)) {
			// 合法用户,跳至欢迎界面
			//request.getRequestDispatcher("welcome.jsp").forward(request, response);
			System.out.println("合法用户名是: "+username);
			request.setAttribute("usr", username);
			
			
			
			return "welcome";
			
		} else {
			// 非法用户,返回登录界面
			//request.getRequestDispatcher("login.jsp").forward(request, response);
			return "login";
			
		}
	};*/

	
	@RequestMapping("showUser.do")
    @ResponseBody  //这个注解 ajax 一般常用
    public String showUser(ModelMap m,String username,String email,String page,String rows,HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		
		
		logger.info("logger显示用户名"+username);
		
        logger.error("username 后的email 故意写成error "+email);
		String rtnString = "";
        try {

            Map<String, Object> a = userService.showUser(username, email, page, rows);

            int total = (Integer) a.get("total");
            String row = (String) a.get("rows");
            m.addAttribute("rows", row);
            
            rtnString = "{\"total\":" + total + ",\n\"rows\":" + row + "\n}";
        } catch (Exception e) {
            e.printStackTrace();
            
        }

        return rtnString;
    }
	
	
	@RequestMapping("searchUser.do")
    @ResponseBody  //这个注解 ajax 一般常用
	public void searchUser(String username,String email,HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=gbk");
		// 接收
		username = request.getParameter("username");
		email = request.getParameter("email");

		String page = request.getParameter("page");
		String rows = request.getParameter("rows");

		Map<String, Object> a = userService.showUser(username, email, page, rows);

		String total = (String) a.get("total");
		String row = (String) a.get("rows");

		response.getWriter().println("{\"total\":" + total + ",\n\"rows\":" + row + "\n}");

	};

	@RequestMapping("editUser.do")
    @ResponseBody  //这个注解 ajax 一般常用
	public String editUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String result="";
		response.setContentType("text/html;charset=gbk");
		String userJsonString = request.getParameter("userJsonString");
		
		logger.info("show userJsonString : "+userJsonString);
		User user = JSON.parseObject(userJsonString, User.class);
		logger.info("show user info: "+ user);
		
		if (userService.editUser(user)) {
			// 编辑用户成功
			
			System.out.println("编辑用户信息成功!");
			//response.getWriter().print(1);
			result="1";
			
			System.out.println("result 值是: "+result);
		} else {
			// 编辑用户失败
			System.out.println("编辑用户信息失败!!!");
			//response.getWriter().print(0);
		}
		System.out.println("编辑后的result值是: "+result);
		return result;
	}
	
	
	@RequestMapping("deleteUser.do")
    @ResponseBody  //这个注解 ajax 一般常用
	public String deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String result="";
		//response.setContentType("text/html;charset=gbk");
		// 接收
		//String userId = request.getParameter("id");
		String userIds = request.getParameter("ids");
		
		if (userService.deleteUser(userIds)) {
			// 删除用户成功
			System.out.println("删除用户信息成功!");
			//response.getWriter().print(1);
			result="1";
		} else {
			// 编辑用户失败
			System.out.println("删除用户信息失败!!!");
			//response.getWriter().print(0);
		}
		System.out.println("删除后的result值是: "+result);
		return result;
	}
	
	
	@RequestMapping("insertUser.do")
    @ResponseBody  //这个注解 ajax 一般常用
	/*@RequestMapping(value="UserServlet",params={"methodName=5"})*/
	public String insertUser(User user,HttpServletRequest request, HttpServletResponse response) {
		
		String result="";
		try {
			
		//response.setContentType("text/html;charset=gbk");
		String userJsonString = request.getParameter("userJsonString");

		user = JSON.parseObject(userJsonString, User.class);

		if (userService.insertUser(user)) {
			// 插入用户成功
			System.out.println("插入用户信息成功!");
			//response.getWriter().print(1);
			result="1";
		} else {
			// 编辑用户失败
			System.out.println("插入用户信息失败!!!");
			//response.getWriter().print(0);
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	// 结束标志位
}